package cn.leetcode;

public class Code42 {
    public static void main(String[] args) {
        int trap = trap(new int[]{0,1,0,2,1,0,1,3,2,1,2,1});
        System.out.println(trap);
    }

    public static int trap(int[] height) {
        int result = 0;
        int a = 0;
        int b = height.length - 1;
        int lh = height[0];
        int rh = height[b];
        while (a != b){
            if(height[a] <= height[b]){
                a++;
                if(height[a] < lh && height[a] < rh){
                    int min = Math.min(lh, rh);
                    int i = min - height[a];
                    result = result + i;
                }
                if(lh < height[a]){
                    lh = height[a];
                }
            } else {
                b--;
                if(height[b] < lh && height[b] < rh){
                    int min = Math.min(lh, rh);
                    int i = min - height[b];
                    result = result + i;
                }
                if(rh < height[b]){
                    rh = height[b];
                }
            }
        }
        return result;
    }

}
